package com.wildfire.conf;

import java.util.List;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.wildfire.model.UserInfo;
import com.wildfire.service.UserService;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    //用于获取用户的角色和权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        List<String> roleList = userInfo.getAccess();
        System.out.println("当前用户权限:" + JSON.toJSONString(roleList));
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleList);
        return simpleAuthorizationInfo;
    }

    //用于检验用户名和密码
    @Override 
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //subject.login到这里
        //从被shiro封装成的token中取出我们传入的username
        String name = (String) authenticationToken.getPrincipal();
		UserInfo userInfo = userService.getUserInfoByName(name);
        return new SimpleAuthenticationInfo(userInfo, userInfo.getPass(), this.getName());
    }
}

